/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */
//发微博控制器
import UIKit
import SVProgressHUD

class LSComposeViewController: UIViewController {
    
    //MARK: - 懒加载控件
    private lazy var rightButton: UIButton = {
        
        let button = UIButton()
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //设置不同状态的文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        //设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        //设置大小
        button.size = CGSize(width: 45, height: 30)
        
        return button
    }()
    
    //MARK: - 标题视图
    private lazy var titleView: UILabel = {
        
        let label = UILabel(fontSize: 18, textColor: UIColor.darkGrayColor())
        if let name = LSUserAccountViewModel.sharedUserAccount.userAccount?.name {
            
            let result = "发微博\n\(name)"
            //获取名称的range
            let range = (result as NSString).rangeOfString(name)
            let attribuedStr = NSMutableAttributedString(string: result)
            
            //添加付文本属性
            attribuedStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(13)], range: range)
            label.attributedText = attribuedStr
            
        } else {
            label.text = "发微博"
        }

        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        
        return label
    }()
    
    //MARK: - 发微博视图
    private lazy var textView: LSComposeTextView = {
        let view = LSComposeTextView()
        view.delegate = self   //设置代理
        view.placeHolder = "被爱的人总是脾气暴躁"
        view.font = UIFont.systemFontOfSize(16)
        view.alwaysBounceVertical = true  //垂直方向开启拖动
        //去掉纠错条
        //中文输入法仍旧会显示(提示条)
        view.autocorrectionType = .No
        
        return view
    }()
    
    //MARK: - toolbar
    private lazy var toolBar: LSComposeToolBar = {
        
        let composeToolbar = LSComposeToolBar(frame: CGRectZero)
        composeToolbar.backgroundColor = UIColor.redColor()
        
        return composeToolbar
    }()
    
    //MARK: - 配图
    private lazy var pictureView: LSComposePictuerView = {
        
        let picView = LSComposePictuerView()
        picView.backgroundColor = self.textView.backgroundColor
        
        return picView
    }()
    
    //MARK: - 表情键盘
    private lazy var emoticonKeyBoard: LSEmoticonKeyBoard = {
        let emoticonKeyBoard = LSEmoticonKeyBoard()
        //指定表情键盘大小
        emoticonKeyBoard.size = CGSize(width: self.textView.width, height: 216)
        
        return emoticonKeyBoard
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //MARK: - 添加控件\设置约束
    private func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        
        //监听键盘改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //监听点击表情的按钮
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmoticon:", name: DidSelectedEmoticonNotification, object: nil)
        
        //监听点击删除表情按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelecteDeleteEmoticon", name: DidSelectedDeleteEmoticonNotification, object: nil)
        
        setupNavUI()
        
        //添加控件
        view.addSubview(textView)
        textView.addSubview(pictureView)
        view.addSubview(toolBar)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(view)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView.snp_width).offset(-10)
            make.height.equalTo(textView.snp_width).offset(-10)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(35)
        }
        
        //MARK: - 分析处理油循环引用 使用
        toolBar.didSelecteToolBarButtonClosuer = { [weak self] (type: LSComposeToolBarButtonType) in
            //根据点击按钮的枚举值进行判断
            switch type {
                
            case .Picture:
                print("图片")
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
                self?.didSelecedEmoticon()
            case .Add:
                print("加号")
                
            }
        }
        //MARK: - 设置配图点击加号的闭包
        pictureView.didSeletedAddimageViewClosure = { [weak self] in
            self?.didSelectedPicture()
        }
    }
    
    //MARK: - 设置导航栏视图
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //设置右边的按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置导航栏的自定义titleView
        navigationItem.titleView = titleView
    }
    //MARK: - 监听点计删除表情按钮的通知方法
    @objc private func didSelecteDeleteEmoticon() {
        //删除textView内容
        textView.deleteBackward()
    }
    
    //MARK: - 监听点击表情的通知方法
    @objc private func didSelectedEmoticon(noti: NSNotification) {
        //获取表情模型
        let emoticon = noti.object as! LSEmoticon
        
        //插入表情富文本
        textView.insertEmoticon(emoticon)
    }
    
    //MARK: - 监听键盘改变的通知方法
    @objc private func keyboardFrameChange(noti: NSNotification) {
        print(noti.userInfo)
        //获取键盘的frame
        let keyBoardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        //获取动画时长
        let duration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - self.view.height)
        }
        
        //更新约束动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK: - 点击事件
    @objc private func cancelAction() {
        //取消第一响应
        self.view.endEditing(true)
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendAction(){

        
        //判断是以否有图片,有图片调用上传图片接口
        if pictureView.images.count > 0 {
            
            upload()
            
        } else {
            update()
        }
    }
    
    //MARK: - 发送文字微博内容
    private func update() {
        //获取微博内容
        let status = textView.emoticonText
        //获取accesstoken
        let accesstoken = LSUserAccountViewModel.sharedUserAccount.accessToken!
        
        //请求发送微博文字接口
        SVProgressHUD.show()
        LSNetworkTools.sharedTools.update(accesstoken, status: status) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络异常请求失败")
                print(error)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }

    }
    
    //MARK: - 发送带图片的微博内容
    private func upload() {
        //获取微博内容
        let status = textView.emoticonText
        //获取accesstoken
        let accessToken = LSUserAccountViewModel.sharedUserAccount.accessToken!
        //获取图片
        let image = pictureView.images.first!
        
        SVProgressHUD.show()
        LSNetworkTools.sharedTools.upload(accessToken, status: status, image: image, callBack: { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络异常, 发送失败")
                print(error)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        })
    }
}



//MARK: - 点击toolbar按钮处理逻辑
extension LSComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //MARK: - 处理点击表情按钮逻辑
    func didSelecedEmoticon() {
        
        if textView.inputView == nil {
            //设置自定义表情键盘
            textView.inputView = emoticonKeyBoard
            toolBar.switchEmotionIcon(true)
        } else {
            //设置为系统键盘
            textView.inputView = nil
            toolBar.switchEmotionIcon(false)
        }
        //设置其为第一响应者
        textView.becomeFirstResponder()
        //重写刷新inputview
        textView.reloadInputViews()
    }
    
    //MARK: - 点击图片逻辑
    func didSelectedPicture() {
        let picCtr = UIImagePickerController()
        picCtr.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            //设置来源类型
            picCtr.sourceType = .Camera
        } else {
            //设置图库
            picCtr.sourceType = .PhotoLibrary
        }
        //MARK: - 判断哪个摄像头可用
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("前置摄像头可用")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("后置摄像头可用")
        } else {
            print("无摄像头可用")
        }
        
        presentViewController(picCtr, animated: true, completion: nil)
    }
    
    //MARK: -UIImagePickerControllerDelegate实现代理方法,如果实现了代理方法直接调用dismis操作
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //let scaleImage = image.scaleImageWithScaleWidth(200)
        //let data1 = UIImagePNGRepresentation(scaleImage)
        //let data2 = UIImageJPEGRepresentation(scaleImage, 0.5)
        //data1?.writeToFile("/Users/apple/Desktop/1.png", atomically: true)
        //data2?.writeToFile("/Users/apple/Desktop/2.png", atomically: true)
        
        //添加配图信息
        pictureView.addImage(image)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    }

//MARK: - 实现UITextViewDelegate代理方法
extension LSComposeViewController: UITextViewDelegate {
    
    //内容改变
    func textViewDidChange(textView: UITextView) {
        //如果有内容则右侧按钮可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    //将要拖动的时候让其失去第一响应者
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        //失去第一响应者
        self.view.endEditing(true)
    }
}










